package com.xtgg.device;

import java.io.FileNotFoundException;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.R.layout;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class DeviceNumberActivity extends BaseActivity implements
		OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_device_number);

		((TextView) findViewById(R.id.center)).setText("设备序列号");

		findViewById(R.id.left).setOnClickListener(this);
		findViewById(R.id.login).setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.left:
			finish();
			break;

		case R.id.login:
			sendHttpRequest();
			break;
		}
	}

	private void sendHttpRequest() {
		String number = ((EditText) findViewById(R.id.number)).getText()
				.toString();
		if (number.length() == 0) {
			ToastUtil.showToastWithAlertPic("请输入序列号");
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("state").equals("1")) {
					ruser = ruser.getJSONArray("data").getJSONObject(0);

					Intent in = new Intent(DeviceNumberActivity.this,
							AddBabyActivity.class);
					in.putExtra("deviceid", ruser.getString("deviceid"));
					startActivity(in);

					finish();
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} 
				else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "connectNewDevice");
		params.put("userid", PreferencesUtils.getString(this, "userid"));
		params.put("devicenumber", number);
		params.put("andriod_code", "");
		params.put("password", "111111");
		params.put("longitude", "");
		params.put("latitude", "");
		params.put("power", "");

		MgqRestClient.get(Constants.DEVICEMGT, params, loginHandler);
	}
}
